import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "qrc:/qml/views/dashboard" as DashboardViews
import "qrc:/qml/components" as Components
import "qrc:/qml/components/simulator" as SimulatorPanels
import "qrc:/qml/styles" as Styles

Page {
    id: simulatorScreen
    title: qsTr("AGV模拟器")

    // ViewModel 绑定
    property var viewModel: GlobalSimulatorViewModel

    // 本地状态（从 ViewModel 同步）
    property bool isPlaying: viewModel ? viewModel.isPlaying : false
    property bool isPaused: viewModel ? viewModel.isPaused : false
    property double simulationSpeed: viewModel ? viewModel.timeScale : 1.0
    property double simulationTime: viewModel ? viewModel.simulationTime : 0.0

    // 侧边栏状态
    property bool sidebarVisible: true
    property int currentSidebarTab: 0  // 0: AGVs, 1: Tasks, 2: Log

    // 选中的AGV
    property var selectedAgv: null

    // 数据模型
    property var agvListModel: GlobalVehicleViewModel ? GlobalVehicleViewModel.agvListModel : null
    property var taskListModel: GlobalTaskViewModel ? GlobalTaskViewModel.taskListModel : null
    property var simulationLogs: []

    background: Rectangle {
        color: Styles.Theme.background
    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 0

        // ==================== 顶部工具栏 ====================
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 60
            color: Styles.Theme.surface
            border.color: Styles.Theme.border
            border.width: 1

            RowLayout {
                anchors.fill: parent
                anchors.leftMargin: Styles.Theme.spacingNormal
                anchors.rightMargin: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingNormal

                // 仿真生命周期控制
                RowLayout {
                    spacing: Styles.Theme.spacingSmall

                    Components.ActionButton {
                        text: isPlaying ? qsTr("▶ 播放中") : qsTr("▶ 播放")
                        buttonType: isPlaying ? "primary" : "secondary"
                        enabled: !isPlaying
                        onClicked: startSimulation()
                    }

                    Components.ActionButton {
                        text: qsTr("❚❚ 暂停")
                        buttonType: isPaused ? "warning" : "secondary"
                        enabled: isPlaying
                        onClicked: togglePause()
                    }

                    Components.ActionButton {
                        text: qsTr("■ 停止")
                        buttonType: "danger"
                        enabled: isPlaying || isPaused
                        onClicked: stopSimulation()
                    }

                    Components.ActionButton {
                        text: qsTr(">> 步进")
                        buttonType: "secondary"
                        enabled: isPaused
                        onClicked: stepSimulation()
                    }
                }

                Rectangle {
                    width: 1
                    height: 30
                    color: Styles.Theme.border
                }

                // 速度控制
                RowLayout {
                    spacing: Styles.Theme.spacingSmall

                    Text {
                        text: qsTr("速度:")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                    }

                    Slider {
                        id: speedSlider
                        from: 0.1
                        to: 5.0
                        value: simulationSpeed
                        stepSize: 0.1
                        Layout.preferredWidth: 150

                        onValueChanged: {
                            if (viewModel && Math.abs(value - viewModel.timeScale) > 0.01) {
                                viewModel.setTimeScale(value)
                            }
                        }
                    }

                    Text {
                        text: speedSlider.value.toFixed(1) + "x"
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        font.weight: Font.Bold
                        Layout.preferredWidth: 40
                    }
                }

                Item { Layout.fillWidth: true }

                // 场景信息和运行状态
                ColumnLayout {
                    spacing: 2
                    Layout.alignment: Qt.AlignVCenter

                    Text {
                        text: viewModel && viewModel.scenarioName ? viewModel.scenarioName : qsTr("默认场景")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        font.weight: Font.Bold
                        Layout.alignment: Qt.AlignHCenter
                    }

                    RowLayout {
                        spacing: 8
                        Layout.alignment: Qt.AlignHCenter

                        Text {
                            text: qsTr("运行时长: ") + (viewModel ? viewModel.duration : "00:00")
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }

                        Text {
                            text: "|"
                            color: Styles.Theme.border
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }

                        Text {
                            text: qsTr("倍率: ") + simulationSpeed.toFixed(1) + "x"
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }
                    }
                }

                Rectangle {
                    width: 1
                    height: 30
                    color: Styles.Theme.border
                }

                // KPI 指标卡片
                RowLayout {
                    spacing: Styles.Theme.spacingNormal

                    // 任务完成率
                    Rectangle {
                        Layout.preferredWidth: 100
                        Layout.preferredHeight: 45
                        color: Styles.Theme.backgroundAlternate
                        radius: Styles.Theme.radiusSmall
                        border.color: Styles.Theme.border
                        border.width: 1

                        ColumnLayout {
                            anchors.centerIn: parent
                            spacing: 2

                            Text {
                                text: viewModel ? viewModel.taskCompletionRate.toFixed(1) + "%" : "0%"
                                color: Styles.Theme.success
                                font.pixelSize: 16
                                font.weight: Font.Bold
                                Layout.alignment: Qt.AlignHCenter
                            }

                            Text {
                                text: qsTr("完成率")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: 9
                                Layout.alignment: Qt.AlignHCenter
                            }
                        }
                    }

                    // 冲突数
                    Rectangle {
                        Layout.preferredWidth: 80
                        Layout.preferredHeight: 45
                        color: Styles.Theme.backgroundAlternate
                        radius: Styles.Theme.radiusSmall
                        border.color: Styles.Theme.border
                        border.width: 1

                        ColumnLayout {
                            anchors.centerIn: parent
                            spacing: 2

                            Text {
                                text: viewModel ? viewModel.conflictCount.toString() : "0"
                                color: viewModel && viewModel.conflictCount > 0 ? Styles.Theme.danger : Styles.Theme.textPrimary
                                font.pixelSize: 16
                                font.weight: Font.Bold
                                Layout.alignment: Qt.AlignHCenter
                            }

                            Text {
                                text: qsTr("冲突")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: 9
                                Layout.alignment: Qt.AlignHCenter
                            }
                        }
                    }

                    // 在线车辆数
                    Rectangle {
                        Layout.preferredWidth: 80
                        Layout.preferredHeight: 45
                        color: Styles.Theme.backgroundAlternate
                        radius: Styles.Theme.radiusSmall
                        border.color: Styles.Theme.border
                        border.width: 1

                        ColumnLayout {
                            anchors.centerIn: parent
                            spacing: 2

                            Text {
                                text: viewModel ? viewModel.onlineVehicleCount.toString() : "0"
                                color: Styles.Theme.info
                                font.pixelSize: 16
                                font.weight: Font.Bold
                                Layout.alignment: Qt.AlignHCenter
                            }

                            Text {
                                text: qsTr("车辆")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: 9
                                Layout.alignment: Qt.AlignHCenter
                            }
                        }
                    }
                }

                Rectangle {
                    width: 1
                    height: 30
                    color: Styles.Theme.border
                }

                // 侧边栏切换
                Components.ActionButton {
                    text: sidebarVisible ? qsTr("隐藏侧栏 ◀") : qsTr("显示侧栏 ▶")
                    buttonType: "secondary"
                    onClicked: sidebarVisible = !sidebarVisible
                }
            }
        }

        // ==================== 主内容区域 ====================
        RowLayout {
            Layout.fillWidth: true
            Layout.fillHeight: true
            spacing: 0

            // 地图视图
            Rectangle {
                Layout.fillHeight: true
                Layout.fillWidth: true
                color: Styles.Theme.backgroundSecondary

                DashboardViews.LiveMapView {
                    id: mapView
                    anchors.fill: parent

                    agvListModel: simulatorScreen.agvListModel

                    onAgvClicked: agvNumber => handleAgvClicked(agvNumber)
                    onStationClicked: stationId => console.log("Station clicked:", stationId)
                    onMapClicked: position => console.log("Map clicked:", position)

                    // TODO: 右键菜单支持
                    // MouseArea {
                    //     anchors.fill: parent
                    //     acceptedButtons: Qt.RightButton
                    //     propagateComposedEvents: true
                    //
                    //     onClicked: mouse => {
                    //         if (mouse.button === Qt.RightButton) {
                    //             contextMenu.popup()
                    //         }
                    //         mouse.accepted = false
                    //     }
                    // }
                }

                // AGV 悬停提示
                ToolTip {
                    id: agvTooltip
                    visible: false
                    delay: 300
                    timeout: 3000

                    contentItem: Column {
                        spacing: 4
                        padding: 8

                        Text {
                            text: qsTr("AGV #") + (selectedAgv ? selectedAgv.agvNumber : "")
                            color: Styles.Theme.textOnPrimary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            font.weight: Font.Bold
                        }

                        Text {
                            text: qsTr("状态: ") + (selectedAgv ? getAgvStatusText(selectedAgv) : "")
                            color: Styles.Theme.textOnPrimary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }

                        Text {
                            text: qsTr("电池: ") + (selectedAgv ? selectedAgv.batteryLevel : 0) + "%"
                            color: Styles.Theme.textOnPrimary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }
                    }

                    background: Rectangle {
                        color: Qt.rgba(0, 0, 0, 0.8)
                        radius: Styles.Theme.radiusSmall
                    }
                }
            }

            // ==================== 可折叠侧边栏 ====================
            Rectangle {
                Layout.fillHeight: true
                Layout.preferredWidth: 350
                Layout.minimumWidth: 300
                Layout.maximumWidth: 500
                visible: sidebarVisible
                color: Styles.Theme.surface
                border.color: Styles.Theme.border
                border.width: 1

                ColumnLayout {
                    anchors.fill: parent
                    spacing: 0

                    // 标签页头部
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 45
                        color: Styles.Theme.backgroundAlternate

                        RowLayout {
                            anchors.fill: parent
                            spacing: 0

                            Repeater {
                                model: [
                                    qsTr("车辆列表"),
                                    qsTr("任务管理"),
                                    qsTr("运行日志")
                                ]

                                delegate: Rectangle {
                                    Layout.fillWidth: true
                                    Layout.fillHeight: true
                                    color: currentSidebarTab === index ? Styles.Theme.primary : "transparent"

                                    Text {
                                        anchors.centerIn: parent
                                        text: modelData
                                        color: currentSidebarTab === index ? Styles.Theme.textOnPrimary : Styles.Theme.textSecondary
                                        font.pixelSize: Styles.Theme.fontSizeNormal
                                        font.weight: currentSidebarTab === index ? Font.Bold : Font.Normal
                                    }

                                    MouseArea {
                                        anchors.fill: parent
                                        cursorShape: Qt.PointingHandCursor
                                        onClicked: currentSidebarTab = index
                                    }
                                }
                            }
                        }
                    }

                    // 标签页内容
                    StackLayout {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        currentIndex: currentSidebarTab

                        // AGVs 标签页 - 使用新组件
                        SimulatorPanels.SimulatorVehiclePanel {
                            vehicleListModel: agvListModel

                            onVehicleSelected: function(agvNumber) {
                                if (agvListModel) {
                                    for (let i = 0; i < agvListModel.rowCount(); i++) {
                                        let agv = agvListModel.getAgvData(i)
                                        if (agv.agvNumber === agvNumber) {
                                            selectedAgv = agv
                                            break
                                        }
                                    }
                                }
                                addLog("info", `选中车辆 AGV${agvNumber}`)
                            }

                            onRefreshRequested: {
                                addLog("info", "刷新车辆配置...")
                                // TODO: 调用 ViewModel 重新加载配置
                                if (GlobalVehicleViewModel) {
                                    // GlobalVehicleViewModel.refreshVehicles()
                                }
                            }

                            onResetRequested: {
                                confirmDialog.title = qsTr("确认重置")
                                confirmDialog.message = qsTr("确认将所有仿真车辆恢复到初始位置？\n该操作会终止当前仿真状态。")
                                confirmDialog.onConfirmed = function() {
                                    addLog("warn", qsTr("正在重置所有仿真车辆"))
                                    if (viewModel) {
                                        viewModel.resetSimulationVehicles()
                                    }
                                }
                                confirmDialog.open()
                            }

                            onCreateVehicleRequested: {
                                vehicleEditorDialog.openForCreate()
                            }
                        }

                        // Tasks 标签页 - 使用新组件
                        SimulatorPanels.SimulatorTaskPanel {
                            taskListModel: simulatorScreen.taskListModel

                            onTaskSelected: function(chainId) {
                                addLog("info", `选中任务 ${chainId}`)
                            }

                            onCreateTaskRequested: {
                                taskDialog.reset()
                                taskDialog.open()
                            }

                            onPauseTaskRequested: function(chainId) {
                                if (GlobalTaskViewModel) {
                                    GlobalTaskViewModel.pauseTask(chainId)
                                    addLog("info", `暂停任务 ${chainId}`)
                                }
                            }

                            onResumeTaskRequested: function(chainId) {
                                if (GlobalTaskViewModel) {
                                    GlobalTaskViewModel.resumeTask(chainId)
                                    addLog("info", `恢复任务 ${chainId}`)
                                }
                            }

                            onCancelTaskRequested: function(chainId) {
                                if (GlobalTaskViewModel) {
                                    GlobalTaskViewModel.cancelTask(chainId)
                                    addLog("warn", `取消任务 ${chainId}`)
                                }
                            }
                        }

                        // Log 标签页 - 使用新组件
                        SimulatorPanels.SimulatorLogPanel {
                            logList: simulationLogs

                            onClearLogsRequested: {
                                clearLogs()
                            }
                        }
                    }
                }
            }
        }

        // ==================== 底部状态栏 ====================
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 35
            color: Styles.Theme.surface
            border.color: Styles.Theme.border
            border.width: 1

            RowLayout {
                anchors.fill: parent
                anchors.leftMargin: Styles.Theme.spacingNormal
                anchors.rightMargin: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingLarge

                // 仿真时间
                Text {
                    text: qsTr("仿真时间: ") + simulationTime.toFixed(2) + "s"
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                    font.weight: Font.Bold
                }

                Rectangle {
                    width: 1
                    height: 20
                    color: Styles.Theme.border
                }

                // 车辆状态（使用 ViewModel 数据）
                Text {
                    text: qsTr("车辆: ") +
                          (viewModel ? viewModel.onlineVehicleCount : 0) + qsTr(" 在线 / ") +
                          (viewModel ? viewModel.idleVehicleCount : 0) + qsTr(" 空闲")
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }

                Rectangle {
                    width: 1
                    height: 20
                    color: Styles.Theme.border
                }

                // 任务状态（使用 ViewModel 数据）
                Text {
                    text: qsTr("任务: ") +
                          (viewModel ? viewModel.completedTaskCount : 0) + qsTr(" 完成 / ") +
                          (viewModel ? viewModel.failedTaskCount : 0) + qsTr(" 失败")
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }

                Rectangle {
                    width: 1
                    height: 20
                    color: Styles.Theme.border
                }

                // 仿真状态
                Text {
                    text: qsTr("状态: ") + getSimulationStatusText()
                    color: isPlaying ? Styles.Theme.success : Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }

                Rectangle {
                    width: 1
                    height: 20
                    color: Styles.Theme.border
                }

                // 冲突警告（如果有冲突则显示）
                Text {
                    visible: viewModel && viewModel.conflictCount > 0
                    text: qsTr("⚠ 冲突: ") + (viewModel ? viewModel.conflictCount : 0)
                    color: Styles.Theme.danger
                    font.pixelSize: Styles.Theme.fontSizeSmall
                    font.weight: Font.Bold
                }

                Item { Layout.fillWidth: true }

                // 仿真引擎状态
                Text {
                    text: viewModel && viewModel.isEnabled ? qsTr("仿真引擎: ✓") : qsTr("仿真引擎: ✗")
                    color: viewModel && viewModel.isEnabled ? Styles.Theme.success : Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }
            }
        }
    }

    // ==================== 函数实现 ====================

    function startSimulation() {
        if (viewModel) {
            viewModel.play()
            addLog("info", "仿真已启动")
        }
    }

    function togglePause() {
        if (viewModel) {
            if (isPaused) {
                viewModel.resume()
                addLog("info", "仿真已恢复")
            } else {
                viewModel.pause()
                addLog("info", "仿真已暂停")
            }
        }
    }

    function stopSimulation() {
        if (viewModel) {
            viewModel.stop()
            clearLogs()
            addLog("info", "仿真已停止")
        }
    }

    function stepSimulation() {
        if (viewModel) {
            viewModel.step(0.1)
            addLog("debug", "步进: " + simulationTime.toFixed(2) + "s")
        }
    }

    function updateSimulation() {
        // ViewModel 自动更新，这里保留以防需要 UI 层面的逻辑
    }

    function handleAgvClicked(agvNumber) {
        console.log("AGV clicked:", agvNumber)

        // 切换到 AGVs 标签页
        currentSidebarTab = 0

        // 选中 AGV
        if (agvListModel) {
            for (let i = 0; i < agvListModel.rowCount(); i++) {
                let agvData = agvListModel.getAgvData(i)
                if (agvData.agvNumber === agvNumber) {
                    selectedAgv = agvData
                    break
                }
            }
        }

        addLog("debug", "选中 AGV #" + agvNumber)
    }

    function createTaskToPoint() {
        addLog("info", "创建任务...")
        // TODO: 实现任务创建
    }

    function forceStopAgv() {
        if (selectedAgv) {
            addLog("warn", "强制停止 AGV #" + selectedAgv.agvNumber)
            // TODO: 实现强制停止
        }
    }

    function resetMapView() {
        addLog("info", "重置地图视图")
        // TODO: 调用地图重置方法
    }

    function clearLogs() {
        simulationLogs = []
    }

    function addLog(level, message) {
        let time = new Date().toLocaleTimeString()
        simulationLogs.push({
            level: level,
            time: time,
            message: message
        })

        // 限制日志数量
        if (simulationLogs.length > 100) {
            simulationLogs.shift()
        }

        // 触发更新
        simulationLogs = simulationLogs.slice()
    }

    // 辅助函数
    function getActiveAgvCount() {
        if (!agvListModel) return 0
        let count = 0
        for (let i = 0; i < agvListModel.rowCount(); i++) {
            let agv = agvListModel.getAgvData(i)
            if (agv.isOnline && agv.isControlled) count++
        }
        return count
    }

    function getTotalAgvCount() {
        return agvListModel ? agvListModel.rowCount() : 0
    }

    function getPendingTaskCount() {
        return GlobalTaskViewModel ? GlobalTaskViewModel.activeTaskCount : 0
    }

    function getSimulationStatusText() {
        if (isPlaying && isPaused) return qsTr("已暂停")
        if (isPlaying) return qsTr("运行中")
        return qsTr("已停止")
    }

    function getAgvStatusColor(isOnline, isCharging, isControlled) {
        if (!isOnline) return Styles.Theme.textSecondary
        if (isCharging) return Styles.Theme.warning
        if (isControlled) return Styles.Theme.info
        return Styles.Theme.success
    }

    function getAgvStatusText(agvModel) {
        if (!agvModel.isOnline) return qsTr("离线")
        if (agvModel.isCharging) return qsTr("充电中")
        if (agvModel.isControlled) return qsTr("执行任务")
        return qsTr("空闲")
    }

    function getTaskStatusColor(status) {
        const colors = {
            "pending": Styles.Theme.warning,
            "executing": Styles.Theme.info,
            "completed": Styles.Theme.success,
            "failed": Styles.Theme.danger,
            "cancelled": Styles.Theme.textSecondary
        }
        return colors[status] || Styles.Theme.textSecondary
    }

    function getLogLevelColor(level) {
        const colors = {
            "error": Styles.Theme.danger,
            "warn": Styles.Theme.warning,
            "info": Styles.Theme.info,
            "debug": Styles.Theme.textSecondary
        }
        return colors[level] || Styles.Theme.textSecondary
    }

    // ==================== 生命周期 ====================

    Component.onCompleted: {
        // 初始化 ViewModel
        if (viewModel) {
            viewModel.initialize()
            addLog("info", "AGV模拟器已加载 - 仿真引擎" + (viewModel.isEnabled ? "已启用" : "未启用"))
        } else {
            addLog("warn", "AGV模拟器已加载 - ViewModel 未找到")
        }
    }

    Component.onDestruction: {
        // 清理 ViewModel
        if (viewModel) {
            viewModel.cleanup()
        }
    }

    // ==================== 对话框 ====================

    // 车辆编辑对话框
    SimulatorPanels.SimulationVehicleEditor {
        id: vehicleEditorDialog
        vehicleListModel: agvListModel

        onVehicleSaved: function(data) {
            addLog("info", `${vehicleEditorDialog.isEditMode ? '更新' : '创建'}车辆: AGV${data.agvNumber} - ${data.name}`)
            console.log("Vehicle saved:", JSON.stringify(data))
        }

        onVehicleDeleted: function(agvNumber) {
            addLog("warn", `删除仿真车辆: AGV${agvNumber}`)
        }
    }

    // 任务创建对话框
    SimulatorPanels.SimulationTaskDialog {
        id: taskDialog
        vehicleListModel: agvListModel
        taskViewModel: GlobalTaskViewModel

        onTaskCreated: function(chainId) {
            addLog("success", `任务已创建: ${chainId}`)
            // 自动切换到任务标签页
            currentSidebarTab = 1
        }
    }

    // 确认对话框（用于重置车辆）
    Components.ConfirmDialog {
        id: confirmDialog
        property var onConfirmed: null

        onAccepted: {
            if (onConfirmed) {
                onConfirmed()
            }
        }
    }
}
